<template>
  <div>
    <h1>用户注册</h1>
    <el-form
      ref="ruleFormRef"
      style="max-width: 600px"
      :model="ruleForm"
      :rules="rules"
      label-width="auto"
    >
      <el-form-item label="手机号" prop="mobile">
        <el-input v-model="ruleForm.mobile" />
      </el-form-item>
      <el-form-item label="密码" prop="pass">
        <el-input v-model="ruleForm.pass" />
      </el-form-item>
      <el-form-item label="验证码" prop="code">
        <el-input v-model="ruleForm.code" style="width: 50%" />
        <el-button type="primary" @click="ongetCode(ruleFormRef)">
          获取验证码
        </el-button>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" @click="submitForm(ruleFormRef)">
          注册
        </el-button>
        <el-button @click="resetForm(ruleFormRef)">重置</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>
<script lang="ts" setup>
import { ref } from "vue";
import { sendCode, userReg } from "../api/api";
import type { FormInstance, FormRules } from "element-plus";
import { ElMessage } from "element-plus";
import { useRouter } from "vue-router";
const router = useRouter();
const ruleFormRef = ref<FormInstance>();
const ruleForm = ref({
  code: "",
  mobile: "",
  pass: "",
});

const rules = ref<FormRules>({
  mobile: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    {
      pattern:
        /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/,
      message: "手机格式错误",
      trigger: "blur",
    },
  ],
  pass: [{ required: true, message: "请输入密码", trigger: "blur" }],
  code: [{ required: true, message: "请输入验证码", trigger: "blur" }],
});

const ongetCode = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validateField(["mobile"], (valid) => {
    if (valid) {
      console.log("submit!");
      sendCode(ruleForm.value.mobile).then((res) => {
        if (res.data.code == 200) {
          ElMessage.success("发送成功");
        } else {
          ElMessage.error(res.data.msg);
        }
      });
    } else {
      console.log("error submit!");
    }
  });
};

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log("submit!");
      userReg(ruleForm.value).then((res) => {
        if (res.data.code == 200) {
          ElMessage.success("注册成功");
          router.push("/login");
        } else {
          ElMessage.error(res.data.msg);
        }
      });
    } else {
      console.log("error submit!", fields);
    }
  });
};

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};

const options = Array.from({ length: 10000 }).map((_, idx) => ({
  value: `${idx + 1}`,
  label: `${idx + 1}`,
}));
</script>
